var express = require('express');
var router = express.Router();
var captchapng = require("captchapng");
var httpUtil = require("../util/httpUtils.js");
var dbHelper = require("../db/db.js");
var Promise = require("bluebird");
var dateUtil = require("../util/dateUtil.js");
var returnHelper = require("../util/returnDataUtil.js");

router.get('/', function (req, res, next) {
    res.render('index', { title: 'Express' });
})

router.get('/captchapng', function(req, res, next) {
    var captchapngCode = parseInt(Math.random()*1000+9000);
    var p = new captchapng(80, 50, captchapngCode);
    p.color(0, 0, 0, 0);
    p.color(255, 255, 255, 255);
    var img = p.getBase64();
    var imgbase64 = new Buffer(img, 'base64');
    req.session.code = captchapngCode;
    res.writeHead(200, {
        'Content-Type': 'image/png'
    });
    res.end(imgbase64);
});

router.get('/getReceiveList', function (req, res, next) {
    var query = req.query;
    var phone = query.phone;
    //dbHelper.db.queryAsync("select latestTime,com,id,orderNum,state,latestInfo from receive where phone = ?", [phone])
    //.then(function (dbData) {
    //    Promise.map(dbData, function (item) {
    //        return httpUtil.getItem({
    //            nu: item.orderNum,
    //            com: item.com
    //        }).then(function (remoteData) {
    //            remoteData = JSON.parse(remoteData);
    //            if(remoteData.success == true) {
    //                var dbLatestTime = new Date(item.latestTime);
    //                var remoteLatestTime = new Date(remoteData.data[0].time);
    //                if(remoteLatestTime.getTime() != dbLatestTime.getTime()) {
    //                    //说明需要更新
    //                    var object = {
    //                        latestTime: dateUtil.basicFormat(remoteLatestTime),
    //                        latestInfo: remoteData.data[0].context,
    //                        state: remoteData.status,
    //                        detail: JSON.stringify(remoteData.data)
    //                    };
    //                    var whereObject = {
    //                        id: item.id
    //                    };
    //                    var dbObject = dbHelper.getUpdateStr('receive', object, whereObject);
    //                    return dbHelper.db.queryAsync(dbObject.str, dbObject.valueArr);
    //                }
    //            }
    //        });
    //    }).then(function () {
    //        dbHelper.db.queryAsync("select latestTime,com,id,orderNum,state,latestInfo from receive where phone = ?", [phone]).then(function (result) {
    //            res.send(returnHelper.init(result));
    //        })
    //    });
    //});
    dbHelper.db.queryAsync("select latestTime,com,id,orderNum,state,latestInfo from receive where phone = ?", [phone])
    .then(function () {
        dbHelper.db.queryAsync("select latestTime,com,id,orderNum,state,latestInfo from receive where phone = ?", [phone]).then(function (result) {
            res.send(returnHelper.init(result));
        });
    });
});

router.get('/addReceive', function (req, res, next) {
    var query = req.query;
    httpUtil.getItem({
        nu: query.nu,
        com: query.type
    }).then(function (remoteData) {
        console.log(remoteData);
        remoteData = JSON.parse(remoteData);
        if (remoteData.success == true) {
            var insertData = {
                phone: query.phone,
                latestTime: dateUtil.basicFormat(new Date(remoteData.data[0].time)),
                latestInfo: remoteData.data[0].context,
                detail: JSON.stringify(remoteData.data),
                orderNum: query.nu,
                com: query.type,
                state: remoteData.status
            };
            var object = {
                phone: insertData.phone,
                orderNum: insertData.orderNum,
                com: insertData.com
            };
            var selectObject = dbHelper.getSelectStr('receive', object);
            //先查找是否有这条记录
            dbHelper.db.queryAsync(
                selectObject.str,
                selectObject.valueArr
            ).then(function (dbData) {
                if (dbData.length) {
                    res.send(returnHelper.error('该运单已存在'));
                } else {
                    var insertObject = dbHelper.getInsertStr('receive', insertData);
                    dbHelper.db.queryAsync(insertObject.str, insertObject.valueArr).then(function (data) {
                        res.send(returnHelper.init());
                    })
                }
            });
        } else {
            res.send(returnHelper.error(remoteData.reason));
        }
    });
});

router.post('/addSend', function (req, res, next) {
    var query = req.body;
    var receiver = JSON.parse(decodeURIComponent(query.receiver));
    var sender = JSON.parse(decodeURIComponent(query.sender));
    var type = parseInt(query.type);
    var sendType = parseInt(query.sendType);
    var nowDate = new Date();
    var nowTime = dateUtil.basicFormat(nowDate);

    var context = "无人机一号正在前往推荐取件点";
    if(sendType!=1){
        context = "快递员正在前往取件";
    }
    var insertObject = {
        receivePhone: receiver.phone,
        receiveName: receiver.name,
        receiveAddress: receiver.address,
        receiveLongitude: receiver.longitude,
        receiveLatitude: receiver.latitude,
        sendPhone: sender.phone,
        sendName: sender.name,
        sendAddress: sender.address,
        sendLongitude: sender.longitude,
        sendLatitude: sender.latitude,
        type: parseInt(type),
        sendType: parseInt(sendType),
        createTime: nowTime,
        latestTime: nowTime,
        latestInfo: context,
        detail: JSON.stringify([{time: nowTime, context: context}]),
        orderNum: dateUtil.getOrderNum(nowDate),
        com: "shunfeng",
        state: "0"
    };
    var insertQuery = dbHelper.getInsertStr('send', insertObject);
    dbHelper.db.queryAsync(insertQuery.str, insertQuery.valueArr).then(function (data) {
        res.send(returnHelper.init({}));
        if(parseInt(sendType)==1){
            console.log(1);
            httpUtil.httpGet("http://115.193.53.158:8000");
        }
    }).error(function (data) {
        res.send(returnHelper.error("似乎出错了"));
    });
});

router.get('/getSendList', function (req, res, next) {
    var query = req.query;
    var phone = JSON.parse(decodeURIComponent(query.phone));
    var selectObject = {
        phone: query.phone
    };
    dbHelper.db.queryAsync("select id,latestTime,latestInfo,detail,orderNum,com,state,type,sendType from send where sendPhone = ?", [phone]).then(function (rows) {
        res.send(returnHelper.init(rows));
    });
});

router.get('/detail', function (req, res, next) {
    var query = req.query;
    var selectObject = {
        id: query.id
    };
    var selectQuery = dbHelper.getSelectStr(query.type, selectObject);
    dbHelper.db.queryAsync(selectQuery.str, selectQuery.valueArr).then(function (data) {
        res.send(returnHelper.init(data[0]));
    });

});

module.exports = router;
